package com.robusta.cityuate.adapters;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.robusta.cityuate.R;
import com.robusta.cityuate.activities.SpotProfileActivity;
import com.robusta.cityuate.base.ViewType;
import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.services.ImageDownloader;

@SuppressLint("SetJavaScriptEnabled")
public class SpotsListAdapter extends BaseAdapter {

	@SuppressWarnings("unused")
	private static final String TAG = SpotsListAdapter.class.getName();
	private Context mContext;
	private LayoutInflater mLayoutInflater;
	private ArrayList<Spot> mEntries = new ArrayList<Spot>();
	private ArrayList<Spot> checkedItems = new ArrayList<Spot>();
	private String mapPage;
	private ViewType.Type ownershipType;

	public ArrayList<Spot> getCheckedItems() {
		return checkedItems;
	}

	public ArrayList<Spot> getmEntries() { 
		return mEntries;
	}

	public void setmEntries(ArrayList<Spot> mEntries) {
		this.mEntries = mEntries;
	}

	private final ImageDownloader mImageDownloader;
	private static final String MAP_URL = "map.html";

	public SpotsListAdapter(Context context,ViewType.Type ownershipType) {
		mContext = context;
		this.ownershipType=ownershipType;
		mLayoutInflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mImageDownloader = new ImageDownloader();
		mapPage="";
		InputStream stream;
		try {
			stream = mContext.getAssets().open(MAP_URL);
			int size = stream.available();
			byte[] buffer = new byte[size];
			stream.read(buffer);
			stream.close();
			mapPage = new String(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		

	}

	@Override
	public int getCount() {
		return mEntries.size();
	}

	@Override
	public Object getItem(int position) {
		return mEntries.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View itemView;
		final Spot spot = mEntries.get(position);
		if (convertView == null)
			itemView = mLayoutInflater.inflate(R.layout.spot_list_item, parent,
					false);
		else
			itemView = convertView;
		itemView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent offering = new Intent(mContext,
						SpotProfileActivity.class);
				offering.putExtra(Spot.SPOT, spot);
				offering.putExtra(ViewType.VIEWTYPE, ownershipType);
				mContext.startActivity(offering);
			}
		});
		ImageView imageView = (ImageView) itemView
				.findViewById(R.id.spot_image);
		TextView spotname = (TextView) itemView.findViewById(R.id.spot_name);
		TextView address = (TextView) itemView.findViewById(R.id.spot_address);
		TextView landmarks = (TextView) itemView
				.findViewById(R.id.spot_landmarks);
		final WebView map = (WebView) itemView.findViewById(R.id.webview);
		CheckBox select = (CheckBox) itemView
				.findViewById(R.id.check_for_action);

		select.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked)
					checkedItems.add(spot);
				else
					checkedItems.remove(spot);
				Log.d("Spots checked count",""+checkedItems.size());
			}
		});

		String imageUrl = spot.getImgURL();
		spotname.setText(spot.getName());
		address.setText(spot.getAddress());
		landmarks.setText(spot.getLandmarks());
		//String loc = "?long=" + spot.getLongt() + "&lat=" + spot.getLat();

		map.getSettings().setJavaScriptEnabled(true);
		map.setWebViewClient(new WebViewClient());

		String spotMap=mapPage.replaceAll("latitudeValue", ""+spot.getLat());
		spotMap=spotMap.replaceAll("longitudeValue", ""+spot.getLongt());
		map.loadData( spotMap, "text/html", "UTF-8");
		

		mImageDownloader.download(imageUrl, imageView);
		return itemView;
	}

	/**
	 * update list of spots after receiving them from service
	 * 
	 * @param entries
	 */
	@SuppressWarnings("unchecked")
	public void updateEntries(ArrayList<Spot> entries) {
		
		mEntries = (ArrayList<Spot>) entries.clone();
		clearCheckedItems();
		notifyDataSetChanged();
	}

	/**
	 * empty list of Checked items.
	 */
	public void clearCheckedItems() {
		checkedItems.clear();
		notifyDataSetChanged();
	}

	public void checkItem(int position) {
		checkedItems.add(mEntries.get(position));
	}

	public void unCheckItem(int position) {
		checkedItems.remove(mEntries.get(position));
	}

	public void toggleCheck(int position) {
		if (checkedItems.contains(mEntries.get(position)))
			checkedItems.remove(mEntries.get(position));
		else
			checkedItems.add(mEntries.get(position));
	}

	public int countCheckedItems() {
		return checkedItems.size();
	}

	public void toggleFavoriteSpot(long id) {
		//Log.e(TAG, "toggle favorite in all list " );
		for (Spot spot : mEntries) {
			if (spot.getId() == id) {
				spot.setIsFavorite(!spot.getIsFavorite());
				break;
			}
		}

		notifyDataSetChanged();
		
	}

}